package work.vcloud.baseinfo.controller;

import work.vcloud.baseinfo.utils.FileUtil;
import work.vcloud.baseinfo.utils.OssUtil;
import work.vcloud.frame.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class UploadController extends BaseController {
	private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

	@Value("${web.upload_path}")
	private String upload_path;
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	@RequestMapping("api/upload")
	@ResponseBody
	public String upload(@RequestParam("mFileName") MultipartFile file) {
		try{
			if (file.isEmpty()) {
				return "上传失败，请选择文件";
			}

			String orgFileName = file.getOriginalFilename();
			//String filePath = upload_path;

			String extName = orgFileName.substring(orgFileName.lastIndexOf(".")+1, orgFileName.length());
			//System.out.println(orgFileName + "-->" + df.format(size) + "-->" + extName);

			String webPath = "DataCenter/" + extName.toUpperCase() + "/" + sdf.format(new Date()).replace("-", "/");
			String uploadPath = upload_path + webPath + "/";

			String newFileName = UUID.randomUUID().toString().replace("-", "");
			newFileName = newFileName + "." + extName.toLowerCase();

			FileUtil.uploadFile(file.getBytes(), uploadPath, newFileName);
			
			//上传文件到对象存储
			String webImageUrl = OssUtil.upload(file.getBytes(), webPath + "/"+newFileName);
			
			LOGGER.info("上传成功");
			return webImageUrl;
		} catch (Exception e) {
			LOGGER.error(e.toString(), e);
		}
		return "上传失败！";



	}


}
